<template>
	<view>
		<view class="u-skeleton u-p-b-80">
			<!-- 商品基础信息 -->
			<goods-base-info :goods="goods" imgHeight="680rpx"></goods-base-info>
			
			<!-- 切换栏 -->
			<view class="u-text-center u-m-t-20">
				<u-tabs :list="sortList" item-width="200" bar-width="160" :current="current" @change="change"></u-tabs>
			</view>
			
			<!-- 商品详情 -->
			<view v-if="current === 0" class="u-p-20">
				<u-parse :html="goods.details"></u-parse>
			</view>
			<!-- 评论 -->
			<view v-if="current === 1">
				<goods-comment :commentList="comments"></goods-comment>
			</view>
			<!-- 相似商品 -->
			<view v-if="current === 2">
				<u-row gutter="16" class="u-skeleton">
					<u-col span="6" v-for="(like_goods,index) in like_goods" :key="index">
						<goods-card :goods="like_goods"></goods-card>
					</u-col>
				</u-row>
				<!-- 相似商品-引用骨架屏组件 -->
				<u-skeleton :loading="loading" :animation="true" bgColor="#FFF"></u-skeleton>
			</view>
			
			<!-- 商品基础信息-引用骨架屏组件 -->
			<u-skeleton :loading="loading" :animation="true" bgColor="#FFF"></u-skeleton>
		</view>
		
		<!-- 提交订单栏 -->
		<submit-bar class="submitBar" :isCollect="goods.is_collect" :cartsCount="cartsCount" 
			@collect="collect" @cartsAdd="cartsAdd">
		</submit-bar>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				goods: {},
				comments: [],
				like_goods: [{},{},{},{}],
				sortList:[
					{name: '详情'},
					{name: '评论',count:0},
					{name: '相似商品'}
				],
				current: 0,
				loading: false,
				cartsCount: 0
			}
		},
		async onLoad(options) {
			// 显示骨架屏
			this.loading = true;
			// 请求API，获取商品详情信息
			const resp = await this.$u.api.goodsDetail(options.id);
			this.goods = resp.goods;
			this.comments = resp.goods.comments;
			this.like_goods = resp.like_goods;
			this.loading = false;// 隐藏骨架屏
			
			this.sortList[1].count = this.comments.length;
			if(this.vuex_token){
				// 加载购物车数量
				const cartsListResp = await this.$u.api.cartsList();
				this.cartsCount = cartsListResp.data.length;
			}
		},
		methods: {
			async change(index){
				this.current = index;
			},
			async collect(){
				if(this.$u.utils.isLogin()){
					// 调用API收藏商品
					await this.$u.api.goodsCollect(this.goods.id)
					if(this.goods.is_collect === 0){
						this.$u.toast("收藏成功")
						this.goods.is_collect = 1
					}else{
						this.$u.toast("取消成功")
						this.goods.is_collect = 0
					}
				}
			},
			/**
			 * 加入购物车
			 */
			async cartsAdd(){
				if(this.$u.utils.isLogin()){
					// 请求API，加入购物车
					await this.$u.api.cartsAdd({goods_id: this.goods.id})
					
					this.$u.toast('添加成功');
					// 重新加载购物车数量
					const resp = await this.$u.api.cartsList();
					this.cartsCount = resp.data.length;
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.submitBar{
		position: fixed;
		bottom: 0;
		left: 0;
	}
</style>
